package org.springframework.social.showcase.config;

import javax.annotation.Resource;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.encrypt.Encryptors;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.social.UserIdSource;
import org.springframework.social.autoconfigure.SocialAutoConfigurerAdapter;
import org.springframework.social.connect.Connection;
import org.springframework.social.connect.ConnectionFactory;
import org.springframework.social.connect.ConnectionFactoryLocator;
import org.springframework.social.connect.ConnectionRepository;
import org.springframework.social.connect.UsersConnectionRepository;
import org.springframework.social.connect.jdbc.JdbcUsersConnectionRepository;
import org.springframework.social.connect.web.ProviderSignInController;
import org.springframework.social.facebook.api.Facebook;
import org.springframework.social.facebook.connect.FacebookConnectionFactory;
import org.springframework.social.showcase.signin.SimpleSignInAdapter;
import org.springframework.social.showcase.user.SecurityContext;
import org.springframework.social.showcase.user.SimpleConnectionSignUp;


/**
 * Created on 2018/1/12.
 *
 * @author zlf
 * @since 1.0
 */
@Configuration
public class FacebookAuthConfig extends SocialAutoConfigurerAdapter {

  @Resource
  private DataSource dataSource;

  @Value("${spring.social.facebook.app-id}")
  String appId;
  @Value("${spring.social.facebook.app-secret}")
  String secret;

  @Override
  protected ConnectionFactory<?> createConnectionFactory() {
    return new FacebookConnectionFactory(appId, secret);
  }


  /**
   * Singleton data access object providing access to connections across all users.
   */
  @Override
  public UsersConnectionRepository getUsersConnectionRepository(
      ConnectionFactoryLocator connectionFactoryLocator) {
    JdbcUsersConnectionRepository repository = new JdbcUsersConnectionRepository(dataSource,
        connectionFactoryLocator, Encryptors
        .noOpText());
    repository.setConnectionSignUp(new SimpleConnectionSignUp());
    return repository;
  }

  @Override
  public UserIdSource getUserIdSource() {
    return () -> {
      String id;
      try {
        id = SecurityContext.getCurrentUser().getId();
      } catch (Exception e) {
        e.printStackTrace();
        id = SecurityContextHolder.getContext().getAuthentication().getName();
      }
      return id;
    };
  }

  @Bean
  @Scope(value = "request", proxyMode = ScopedProxyMode.INTERFACES)
  public Facebook facebook(ConnectionRepository repository) {
    Connection<Facebook> connection = repository.findPrimaryConnection(Facebook.class);
    return connection != null ? connection.getApi() : null;
  }

  @Bean
  public ProviderSignInController providerSignInController(
      ConnectionFactoryLocator connectionFactoryLocator,
      UsersConnectionRepository usersConnectionRepository) {
    return new ProviderSignInController(connectionFactoryLocator, usersConnectionRepository,
        new SimpleSignInAdapter(new HttpSessionRequestCache()));
  }
}
